# -*- coding:utf-8 -*-
import json
import time
from flask import request,session,render_template

from . import app,wm,db
from .models import bank_logger, message_logger
from . import utils

import random

call_time = random.randint(1,99999999999)
@app.route("/getAndLockTicket")
def getAndLockTicket():
    global call_time
    call_time +=1
    user_account = request.args.get("user_account",'')
    app.logger.debug("start  {func} in {time}".format(func="getAndLockTicket",time=utils.create_time()))

    # print(call_time)
    # wid = call_time
    # money = str(1)
    # bank_name = "鲍江珊"
    # bank_account = "6214180000003536128"
    # bank_name = "伍镜滔"
    # bank_account = '6216910310953549'

    # return json.dumps({"wid":wid,"money":money,"bank_name":bank_name,"bank_account":bank_account,"err":0,"errMsg":""})
    
    level = request.args.getlist('level[]')
    print(level)
    r = wm.catchTicket(level)

    if len(r[1]) == 0:
        return json.dumps({"err":1,"errMsg":"no mission"})
    elif session.get("wid",None) is not None:
        return json.dumps({"err":2,"errMsg":"last mission {wid} is not commit".format(wid=str(session['wid']))})
    else:
        wid = list(r[1].keys())[0]
        res = wm.lockTicket(wid,"自动化锁定测试.")
        if res is None:
            return json.dumps({"err":1,"errMsg":"no mission"})
        money = r[1].get(wid)['金额']
        bank_info = res[2] 
        print(bank_info)
        
        try:
            bank_name = bank_info['account_name']
        except Exception as e:
            bank_name = bank_info['realname']
    
        bank_account = bank_info['account']
        start_time = utils.create_time()
        b=bank_logger.query.filter_by(wid=wid).first()
        if b is None:
            b = bank_logger(wid=wid,uid=user_account,money=money,bank_name=bank_name,bank_account=bank_account,start_time=start_time)
            db.session.add(b)
            db.session.commit()
        session['wid'] = wid

        return json.dumps({"wid":wid,"money":money,"bank_name":bank_name,"bank_account":bank_account,"err":0,"errMsg":""})

@app.route("/markTicket")
def markTicket():
    wid = request.args.get("wid",None)
    message = request.args.get("message","")
    if wid is None:
        wid = session.get("wid",None)
    if wid is None:
        return json.dumps({"err":3,"errMsg":"no wid"})
    if message == '':
        return json.dumps({"err":7,"errMsg":"no message"})
    wm.markTicket(wid,message)
    return json.dumps({"err":0,"errMsg":""}) 

@app.route("/unlockTicket")
def unlockTicket():
    wid = request.args.get("wid",None)
    message = request.args.get("message","")
    if wid is None:
        wid = session.get("wid",None)
    if wid is None:
        return json.dumps({"err":3,"errMsg":"no wid"})
    else:
        app.logger.debug("start  {func} with wid={wid},message={message} in {time}".format(func="commit",time=utils.create_time(),wid=wid,message=message))
        
        wm.unlockTicket(wid,message)
        b=bank_logger.query.filter_by(wid=wid).first()
        if b is not None:
            b.is_lock = False
            db.session.commit()
        session['wid'] = None
        return json.dumps({"err":0,"errMsg":""})

@app.route("/commit")
def commit():
    wid = None
    try:
        wid = session['wid']
        session['wid'] = None
    except Exception as e:
        wid = request.args.get("wid",None)

    if wid is None:
        return json.dumps({"err":3,"errMsg":"no wid"}) 
    
    wm.submitTicket(wid)

    app.logger.debug("start  {func} with {args} in {time}".format(func="commit",time=utils.create_time(),args=wid))

    b=bank_logger.query.filter_by(wid=wid).first()
    if b is not None:
        b.is_lock = 0
        b.is_finish = 1
        db.session.commit()
    print(session.get("wid",None))
    return str(wid)

@app.route("/messageService",methods=['POST','GET','PUT'])
def messageService():
    "获取短信用get,提交短信用post"
    if request.method == 'POST':
        sender_phone = request.form.get("sender_phone")
        IMSI = request.form.get("IMSI")
        content = request.form.get("content")
        create_time = utils.create_time()
        app.logger.debug("new message in {time} from {sender_phone} to {IMSI} with message :\n{content}".format(sender_phone=sender_phone,IMSI=IMSI,time=create_time,content=content))
        m=message_logger.query.filter(message_logger.content == content , message_logger.create_time > utils.create_time_nmin_before(5) ).order_by(message_logger.create_time.desc()).first()
        if m is None:
            m = message_logger(sender_phone=sender_phone,IMSI=IMSI,content=content,create_time=create_time)
            db.session.add(m)
            db.session.commit()
            return json.dumps({"err":0,"errMsg":"","msg":"保存短信成功"})
        else:
            return json.dumps({"err":4,"errMsg":"已有时间相近且内容相同的短信"})
    elif request.method == 'GET':
        IMSI = request.args.get("IMSI","")
        sender_phone = request.args.get("sender_phone","")
        app.logger.info("请求接收号码的IMSI:{IMSI},发送号码:{sender_phone}的短信".format(IMSI=IMSI,sender_phone=sender_phone))
        if IMSI == "" or sender_phone == "":
            return json.dumps({"err":5,"errMsg":"query args error"})
        m = message_logger.query.filter(message_logger.IMSI == IMSI , message_logger.sender_phone == sender_phone , message_logger.create_time > utils.create_time_nmin_before(4) , message_logger.is_use == 0).order_by(message_logger.create_time.desc()).first()
        if m is None:
            return json.dumps({"err":6,"errMsg":"暂无短信"})
        else:
            m.is_use = 1
            db.session.commit()
            return json.dumps({"err":0,"errMsg":"","data":m.toJson()})
        


@app.route("/showLockedList",methods=['GET'])
def showLockedList():
    return str(wm.locked)
    #return json.dumps({"err":0,"errMsg":"","data":wm.locked})

@app.route("/checkIsLocked",methods=['GET'])
def checkIsLocked():
    wid = request.args.get("wid",None)
    if wid is None:
        wid = session.get("wid",None)
    user_account = request.args.get("user_account",'')
    result = wm.checkIsLocked(wid)
    return json.dumps({"err":0,"errMsg":"","data":result})

@app.route("/login",methods=['GET','POST'])
def relogin_wm():
    if request.method == 'GET':
        alive = False
        try:
            alive = wm.catchTicket()
        except Exception as e:
            alive = False
        if alive != False:
            alive = True
        return render_template("login.html",alive = alive)
    else:
        username = request.form.get("username",'')
        password = request.form.get("password",'')
        otp = request.form.get("otp",'')
        print(username,password,otp)
        if otp != '' and len(otp) == 6:
            wm.username = username
            wm.password = password
            wm.otp = otp
            return wm.login()
        return "fail"

@app.route("/config",methods=['GET','POST'])
def config():
    if request.method == 'GET':
        return render_template("config.html",config=app.config)
    else:
        pass
        # username = request.form.get("username",'')
        # password = request.form.get("password",'')
        # otp = request.form.get("otp",'')

        # if otp != '' and len(otp) == 6:
        #     wm.username = username
        #     wm.password = password
        #     wm.otp = otp
        #     return wm.login()
        # return "fail"

@app.route("/test",methods=['GET','POST'])
def test():
    print(request.args.getlist('level'))
    print(request.form)
    print(request.data)
    return ''